﻿namespace SimpleWebServices.Web.Mvc
{
    using System;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using System.Xml;

    public abstract class RedirectionResult : ActionResult
    {
        protected RedirectionResult()
            : this("/")
        {
        }

        protected RedirectionResult(string location)
        {
            if (null == location)
            {
                throw new ArgumentNullException("location");
            }
            else if (0 == location.Length)
            {
                throw new ArgumentOutOfRangeException("location");
            }

            this.Location = location;
        }

        public string Location
        {
            get;
            set;
        }

        public abstract HttpCacheability Cacheability
        {
            get;
        }

        public abstract HttpStatusCode StatusCode
        {
            get;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (null == context)
            {
                throw new ArgumentNullException("context");
            }

            HttpResponseBase response = context.HttpContext.Response;

            AbsoluteUri location = null;
            if (this.Location.Contains("://"))
            {
                location = new Uri(this.Location);
            }
            else
            {
                location = new Uri(context.HttpContext.Request.Url, new Uri(this.Location, UriKind.Relative));
            }

            response.StatusCode = (int)this.StatusCode;
            response.AppendHeader("Location", location);

            response.Cache.SetCacheability(this.Cacheability);
            response.Cache.SetExpires(DateTimeFactory.UtcNow.AddDays(1));

            response.ContentType = "text/html";

            XmlDocument content = new XmlDocument();
            content.LoadXml(
                "<html>" +
                "<head>" +
                "<title>The information you requested has been found</title>" +
                "<meta value='" + DateTime.UtcNow.ToXmlString() + "' />" +
                "</head>" +
                "<body>" +
                "<h1>The information you requested has been found</h1>" +
                "<p><a id=\"location\" href=\"\"></a></p>" +
                "</body>" +
                "</html>");
            content.SelectSingleNode("/html/body/p/a[@id='location']/@href").Value = location;
            content.SelectSingleNode("/html/body/p/a[@id='location']").InnerText = HttpUtility.HtmlEncode(location);

            response.Write(content.OuterXml);
        }
    }
}